package ani.trainning.cacobatph.situation;

import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import ani.trainning.cacobatph.R;
import ani.trainning.cacobatph.utilities;

public class ThreadSituation {


	public static final int ERREUR_LOCAL = -1;
	public static final int ERREUR_WS = 0;
	public static final int RESULT_OK = 1;


	private final Handler mHandler;
	private final Context context;

	boolean noErrorServer = true;

	String user;
	String pass;

	// constructor
	public ThreadSituation(Handler handler, Context context,String _user, String _pass) {
		mHandler = handler;
		this.context = context;
		this.user=_user;
		this.pass=_pass;
	}

	public Thread createThread() {
		return new Thread() {
			@Override
			public void run() {
				// creation du message.
				try {

					String response = decoderJson(utilities.cacoSimulation(context, user,pass,context.getResources().getString(R.string.ws08_dac_method)));
					Message msg=new Message();
					msg.what = RESULT_OK;
					msg.obj = response;
					if(!noErrorServer)
						msg.what = ERREUR_WS;
					mHandler.sendMessage(msg);

				} catch (Exception e) {
					Message msg=new Message();
					msg.what = ERREUR_LOCAL;
					msg.obj = "" + e.getMessage();
					mHandler.sendMessage(msg);
				}

			}
		};
	}

	private String decoderJson(String response) throws Exception{

		JSONObject jSon = new JSONObject(response);
		int code = jSon.getInt("code");
		switch (code) {
		case 3:
			return jSon.getString("description");
		case 4:
			return jSon.getString("description");
		case 5:
			noErrorServer = false;
			return response;
		default:

			return response;
		}


	}

}
